<?php 

class Helper_Form extends Zend_Controller_Action_Helper_Abstract {
	
	private $class;
	private $jsonize;
	private $where;// do load - jak jest to id requestu ignorowane (moze być zawarte w where)
	private $columns;
	private $order;
	private $pk;
	
	public function direct(My_Model $class,$jsonize = true,$join = null,$where = null,$columns = null,$order = null){
		$this->class 	= $class;
		$this->jsonize 	= $jsonize;
		$this->join 	= $join;
		$this->order	= $order;
		$this->columns	= $columns;
		$this->where	= $where;
		$this->pk 		= Utils::arrayFetch($this->class->info('primary'));
		$operation = $this->getRequest()->getParam('my_action_type')=='load'? 
			'load':'save';
		return $this->$operation();
	}
	
	public function load(){
		$id = $this->getRequest()->getParam('id');
		$where = $this->where ? $this->where : Utils::quote($this->class->info('name').".$this->pk = ?",$id);
		$row = $this->class->q($where, $this->join,$this->order)->fetchObject();
		return $this->respond($row,'load');
	}
	
	public function save(){
		$test = ($this->getRequest()->getParam($this->pk)=='');
		// editBlock - tylko na updacie! 
		$fields = Utils::matches(
			$this->getRequest(), 
			$this->class->info('cols'), 
			$this->class->emptyToNull,
			$this->columns,
			$test?array():$this->class->editBlock
		);
		
		unset($fields[$this->pk]);
		
		return $test ? $this->insert($fields) : $this->update($fields);
	}
	
	public function insert($fields){
		return $this->respond($this->class->insert($fields),'insert');
	}
	
	public function update($fields){
		$where = Utils::quote($this->pk.'= ?',$this->getRequest()->getParam($this->pk));
		return $this->respond($this->class->update($fields,$where),'update');
	}
	
	public function respond($result,$operation){
		
		switch ($operation) {
			case 'load':
				$success = is_object($result);
				break;
			case 'insert':
				$success = $result != 0;
				break;
			case 'update':
				$result = $this->getRequest()->getParam($this->pk);
				$success = true;// bo 0 znaczy ze nic sie nie zmieniło
				break;
		}
		$resp = array("success"=>$success,"data"=>$result,"operation"=>$operation);
		return $this->jsonize ? json_encode($resp) : $resp;
	}
	
}


?>